package com.pro01.backend.controller;

import com.pro01.backend.pojo.ForumComment;
import com.pro01.backend.pojo.ForumPost;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.ForumCommentService;
import com.pro01.backend.service.ForumPostLikeService;
import com.pro01.backend.service.ForumPostService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/posts") // ✅ 注意这点
public class PostController {

    @Autowired
    private ForumPostService forumPostService;

    @Autowired
    private ForumCommentService forumCommentService;

    @Autowired
    private ForumPostLikeService forumPostLikeService;

    /**
     * 查看帖子详情（自动浏览量 +1）
     */
//    @GetMapping("/{postId}")
//    public Result<ForumPost> getPostDetail(@PathVariable Long postId,
//                                           HttpServletRequest request) {
//        try {
//            TokenUtil.getUserId(request); // 仅校验登录
//            ForumPost post = forumPostService.getPostDetail(postId);
//            return Result.success(post);
//        } catch (Exception e) {
//            return Result.error("获取帖子失败：" + e.getMessage());
//        }
//    }
    @GetMapping("/{postId}")
    public Result<ForumPost> getPostDetail(@PathVariable Long postId,
                                           HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            ForumPost post = forumPostService.getPostDetail(postId, userId);
            return Result.success(post);
        } catch (Exception e) {
            return Result.error("获取帖子失败：" + e.getMessage());
        }
    }

    /**
     * 编辑帖子
     */
    @PutMapping("/{postId}")
    public Result<Void> updatePost(@PathVariable Long postId,
                                   @RequestBody Map<String, String> requestBody,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            String title = requestBody.get("title");
            String content = requestBody.get("content");

            forumPostService.updatePost(postId, userId, title, content);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("编辑帖子失败：" + e.getMessage());
        }
    }

    /**
     * 用户删除帖子(软删除)
     */
    @DeleteMapping("/{postId}")
    public Result<Void> deletePost(@PathVariable Long postId,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            forumPostService.deletePost(postId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除帖子失败：" + e.getMessage());
        }
    }

    /**
     * 用户模糊查询帖子
     */
    @GetMapping
    public Result<PageResult<ForumPost>> searchPostsByTitle(
            @RequestParam String title,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            PageResult<ForumPost> pageResult = forumPostService.searchPostsByTitle(title, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索帖子失败：" + e.getMessage());
        }
    }

    /**
     * 用户查看自己发的所有帖子
     */
    @GetMapping("/mine")
    public Result<PageResult<ForumPost>> getMyPosts(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户 ID
            PageResult<ForumPost> pageResult = forumPostService.getPostsByUser(userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户自己的帖子失败：" + e.getMessage());
        }
    }

    /**
     * 用户隐藏自己的帖子
     */
    @PutMapping("/{postId}/hide")
    public Result<Void> hideMyPost(@PathVariable Long postId,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户 ID
            forumPostService.hidePostByUser(postId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("隐藏帖子失败：" + e.getMessage());
        }
    }

    /**
     * 用户取消隐藏自己的帖子
     */
    @PutMapping("/{postId}/restore")
    public Result<Void> restoreMyPost(@PathVariable Long postId,
                                      HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户 ID
            forumPostService.restorePostByUser(postId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("恢复帖子失败：" + e.getMessage());
        }
    }

    /**
     * 接下来是评论接口
     */

    /**
     * 用户在帖子下发表评论
     */
    @PostMapping("/{postId}/comments")
    public Result<Void> addComment(@PathVariable Long postId,
                                   @RequestBody ForumComment comment,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 当前登录用户

            comment.setPostId(postId);
            comment.setUserId(userId);

            forumCommentService.addComment(comment);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发表评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户查看某个帖子下的评论列表（分页）
     */
    @GetMapping("/{postId}/comments")
    public Result<PageResult<ForumComment>> getCommentsByPost(
            @PathVariable Long postId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request); // 仅用于校验登录
            PageResult<ForumComment> pageResult = forumCommentService.getCommentsByPost(postId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户删除自己发的评论
     */
    @DeleteMapping("/{postId}/comments/{commentId}")
    public Result<Void> deleteMyComment(@PathVariable Long postId,
                                        @PathVariable Long commentId,
                                        HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            forumCommentService.deleteCommentByUser(commentId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户隐藏自己发的评论
     */
    @PutMapping("/{postId}/comments/{commentId}/hide")
    public Result<Void> hideMyComment(@PathVariable Long postId,
                                      @PathVariable Long commentId,
                                      HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            forumCommentService.hideCommentByUser(commentId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("隐藏评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户恢复自己隐藏的评论
     */
    @PutMapping("/{postId}/comments/{commentId}/restore")
    public Result<Void> restoreMyComment(@PathVariable Long postId,
                                         @PathVariable Long commentId,
                                         HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            forumCommentService.restoreCommentByUser(commentId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("恢复评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户查看自己在某个帖子下发的评论（分页）
     */
    @GetMapping("/{postId}/comments/mine")
    public Result<PageResult<ForumComment>> getMyCommentsByPost(
            @PathVariable Long postId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            PageResult<ForumComment> pageResult = forumCommentService.getMyCommentsByPost(postId, userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户自己的评论失败：" + e.getMessage());
        }
    }

    /**
     * 用户点赞帖子
     */
    @PostMapping("/{postId}/like")
    public Result<Void> likePost(@PathVariable Long postId,
                                 HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            forumPostLikeService.likePost(userId, postId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    /**
     * 用户取消点赞帖子
     */
    @DeleteMapping("/{postId}/like")
    public Result<Void> unlikePost(@PathVariable Long postId,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            forumPostLikeService.unlikePost(userId, postId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }

}
